const Router = require('koa-router');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const registerRedis = require('../redis/redisregister');
const loginRedis = require('../redis/redislogin');
const { getCode } = require('../model/register');
const createToken = require('../token/createToken');
let router = new Router();

router.get('/',async (ctx) => {
  ctx.body = "这是用户首页";
})

router.post('/getverifycode',async (ctx,next) => {
  const User = mongoose.model('User');
  let phoneNumber = ctx.request.body.phoneNumber;
  let code = getCode(phoneNumber);
  let user = await User.findOne({
    phoneNumber,
  }).exec();
  ctx.status=200;
  let existPhoneCode = await registerRedis.get(phoneNumber);
  if(!user){
    // redis取值判断
    if(!existPhoneCode) {
      registerRedis.set(phoneNumber,code, "EX", 60*3);
      ctx.body = {
        code: 200,
        message: "发送成功",
        data: {
          code,
        }
      }
    } else {
      console.log("存在")
      ctx.body = {
        code: 400,
        message: "验证码已发送,请查收验证码",
        data: {code: existPhoneCode},
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: "已有账户请直接登录",
    }
  }
  await next();
})

router.post('/register',async (ctx, next) => {
  const User = mongoose.model('User');
  ctx.status = 200;
  let { username, password, phoneNumber, captcha } = ctx.request.body;
  let user = await User.findOne({
    userName: username,
  }).exec();
  let phone = await User.findOne({
    phoneNumber,
  }).exec();
  if(!user) {
    if(!phone) {
      let existPhoneCode = await registerRedis.get(phoneNumber);
      console.log(existPhoneCode == captcha.toString())
      if(existPhoneCode === captcha) {
        const newUser = new User({userName: username,password,phoneNumber,createAt: new Date()});
        let saveResult = await newUser.save();
        if(saveResult) {
          ctx.body = {
            code: 200,
            message: "注册成功",
          }
        }else {
          ctx.body = {
            code: 500,
            message: "服务器错误",
          }
        }
      } else {
        ctx.body = {
          code: 400,
          message: "验证码错误或已过期",
        }
      }
    } else {
      ctx.body = {
        code: 400,
        message: "手机号码已被注册",
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: "用户名已存在",
    }
  }
  await next();
})

router.post('/login',async (ctx,next) => {
  const User = mongoose.model('User');
  let oneDayTimes = 24*60*60;
  ctx.status=200;
  const loginInfo = ctx.request.body;
  let user = await User.findOne({
    userName: loginInfo.userName,
  }).exec();
  if(user) {
    const validate = await bcrypt.compareSync(loginInfo.password,user.password);
    if(validate) {
      let { userId, userName, grade, phoneNumber,createAt } = user;
      let token = createToken({userId, userName, grade, phoneNumber,createAt},oneDayTimes);
      loginRedis.set(userName, token, "EX", 60*60*24);
      ctx.body = {
        code: 200,
        message: "登录成功",
        data: {
          token,
          userId,
          userName,
          grade,
          phoneNumber,
          createAt,
        }
      }
    } else {
      ctx.body = {
        code: 400,
        message: "密码错误"
      }
    }
  } else {
    ctx.body = {
      code: 400,
      message: "账户名不存在"
    }
  }
  await next();
})

module.exports = router;